/**
 * 
 */
package org.istt.export;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.istt.domain.AttachFileDetail;
import org.istt.domain.File;
import org.istt.web.WebConstants;

/**
 * @author NDTHO
 *
 */
public class ReceiptCreator extends BaseReport{
	
	// So bien nhan ho so
	private String serial = "$Serial$";
	
	// So thu tu ho so
	private String index = "$Index$";
	
	// Ngay...thang...nam
	private String today = "$Today$";

	// Ten thu tuc hanh chinh
	private String category = "$Category$";
	
	// Ten thu tuc hanh chinh con
	private String subCategory = "$Sub_Category$";
	
	// Ho ten nguoi dung ten ho so
	private String submiter = "$Submiter$";
	
	// Dia chi lien he
	private String address = "$Address$";
	
	// Ho ten nguoi lien he
	private String contact = "$Contact$";
	
	// Dien thoai lien he
	private String contactPhone = "$Contact_Phone$";

	// Fax lien he
	private String contactFax = "$Contact_Fax$";
	
	// Thoi gian xu ly ho so
	private String processTime = "$Process_Time$";
	
	// Ngay hen tra ho so
	private String outputDate = "$Output_Date$";
	
	// Ho va ten nguoi nop ho so
	private String sender = "$Sender$";
	
	// Ho va ten nguoi nhan ho so
	private String receiver = "$Receiver$";
	
	// Dia chi cong trinh xay dung
	private String location = "$Location$";
	
	// Ten cong trinh
	private String construct = "$Building$";
	
	// Nha thau nuoc ngoai
	private String contractor = "$Contractor$";

	// Dien thoai cua nha thau
	private String contractorTel = "$ContractorTel$";

	// Fax cua nha thau
	private String contractorFax = "$ContractorFax$";
	
	
	private String organization = "$Organization$";
	
	private String organizationTel = "$OrganizationTel$";

	private String organizationFax = "$OrganizationFax$";
	
	// Giay to khac
	private String otherAttachFile = "$OtherAttachFile$";
	
	// So TT
	private String no = "$List_No$";
	
	// Ten giay to 
	private String documentName = "$List_Document_Name$";
	
	// So luong giay to
	private String documentNumber = "$List_Document_Number$";
	
	// Ban chinh
	private String symbolMain = "$List_Sym_M$";
	
	// Ban photo
	private String symbolPhoto = "$List_Sym_P$";
	
	// Ban photo cong chung
	private String symbolMainPhoto = "$List_Sym_MP$";

	// Ngay ky duyet ho so
	private String approvedDate = "$ApprovedDate$";
	
	
	public InputStream toMSWord(InputStream docFile,File f, List<AttachFileDetail> attFileDetails) throws IOException {
	    
	    XWPFDocument docx = new XWPFDocument(docFile);
	    Iterator<XWPFTable> range=docx.getTablesIterator();
	    
	    while(range.hasNext()){
		    
	    	XWPFTable tableHeader=range.next();
	    	
	    	readTable(tableHeader,attFileDetails, f);
	    }
	    
	    //write to word file
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    docx.write(baos);
	    
	    return new ByteArrayInputStream(baos.toByteArray());
	}
	
	public void readTable(XWPFTable table, List<AttachFileDetail> attFileDetails, File f){
		List<XWPFTableRow> lstRows = table.getRows();
		boolean isIterator = false;
		ArrayList<String> lstElement = new ArrayList<String>();
		
        for (Iterator<XWPFTableRow> iterator = lstRows.iterator(); iterator.hasNext();) {
			XWPFTableRow xwpfTableRow = (XWPFTableRow) iterator.next();
			
			if(isIterator) continue;
			
			List<XWPFTableCell> lstCells = xwpfTableRow.getTableCells();
			for (Iterator<XWPFTableCell> iterator2 = lstCells.iterator(); iterator2.hasNext();) {
				XWPFTableCell xwpfTableCell = (XWPFTableCell) iterator2.next();
				List<XWPFParagraph> lstParagraph = xwpfTableCell.getParagraphs();
				
				for (Iterator<XWPFParagraph> iterator3 = lstParagraph.iterator(); iterator3.hasNext();) {
					XWPFParagraph xwpfParagraph = (XWPFParagraph) iterator3.next();
					
					System.out.println(" -- "+xwpfParagraph.getParagraphText());
					
					String strText = xwpfParagraph.getParagraphText();
					
					if(strText.contains("$List")){
						
						lstElement.add(strText);
						
						isIterator = true;
						
					}else{
						
						replaceString(xwpfParagraph,this.serial,f.getNumber().toString());
						replaceString(xwpfParagraph,this.index,f.getId());
						
						DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
						Date dateToday = new Date();
						String strDate =  dateFormat.format(dateToday);
						String strToday = " ng\u00E0y "+strDate.substring(0, 2)+" th\u00E1ng "+strDate.substring(3, 5)+" n\u0103m "+strDate.substring(6, 10) ;
						replaceString(xwpfParagraph,this.today,strToday);
						
						replaceString(xwpfParagraph,this.category,f.getCategory().getCategoryName());
						replaceString(xwpfParagraph,this.subCategory,getSubCategoryName(f.getSubCategory()));
						
						replaceString(xwpfParagraph,this.submiter,f.getSubmitter());
						replaceString(xwpfParagraph,this.address,f.getAddress());
						replaceString(xwpfParagraph,this.contact,f.getContactName());
						replaceString(xwpfParagraph,this.contactPhone,f.getContactPhone());
						replaceString(xwpfParagraph,this.contactFax,f.getContactFax());
						replaceString(xwpfParagraph,this.processTime,f.getCategory().getProcessTime());
						replaceString(xwpfParagraph,this.otherAttachFile,f.getOtherAttachFiles());

						replaceString(xwpfParagraph,this.construct,f.getConstruct());
						replaceString(xwpfParagraph,this.contractor,f.getOversea());
						replaceString(xwpfParagraph,this.contractorTel,f.getOverseaPhone());
						replaceString(xwpfParagraph,this.contractorFax,f.getOverseaFax());
						replaceString(xwpfParagraph,this.location,f.getLocation());
						replaceString(xwpfParagraph,this.organization,f.getOrganization());
						replaceString(xwpfParagraph,this.organizationTel,f.getOrgPhone());
						replaceString(xwpfParagraph,this.organizationFax,f.getOrgFax());
						
						String dateStr = f.getOutputDate().toString();
						
						replaceString(xwpfParagraph,this.outputDate,"Ng\u00E0y "
								+ dateStr.substring(8, 10)
								+ " th\u00E1ng "
								+ dateStr.substring(5, 7)
								+ " n\u0103m "
								+ dateStr.substring(0, 4)
								+ ", "
								+ f.getOutputDate().dayOfWeek().getAsText(new Locale("vi")));
						
						replaceString(xwpfParagraph,sender,f.getSender());
						replaceString(xwpfParagraph,receiver,f.getCreatedBy().getFullname());
					}
				}
			}
		}
        if(isIterator){
        	createRow(table, attFileDetails, lstElement);
        }
	}
	
	private void createRow(XWPFTable table, List<AttachFileDetail> attFileDetails, ArrayList<String> lstElement){
		// Call create row
    	
    	int counter = 1;
    	
    	try {
    		table.removeRow(1);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	for (Iterator<AttachFileDetail> iterator4 = attFileDetails.iterator(); iterator4.hasNext();) {
    		AttachFileDetail attachFileDetail = (AttachFileDetail) iterator4.next();
    		
    		XWPFTableRow content_row = table.createRow();
    		
    		if(attachFileDetail.getAttachFile().getHeading()!=null && attachFileDetail.getAttachFile().getHeading()){
        		//Reset counter for next items
        		counter = 1;
        		
        		XWPFRun column2 = content_row.getCell(1).getParagraphs().get(0).createRun();
        		setTextFormat(column2, attachFileDetail.getAttachFile().getAttachFileName(), FONT_SIZE_11, true, false, FONT_TIMES_NEW_ROMAN);
        		setAlignment(content_row.getCell(1).getParagraphs().get(0), LEFT_ALIGN, SPACING_0, SPACING_06);
    		}else{
        		int cellNumber = 0;
        		for (Iterator<String> iterator = lstElement.iterator(); iterator.hasNext();) {
					String strKey = (String) iterator.next();
					XWPFRun run = content_row.getCell(cellNumber).getParagraphs().get(0).createRun();
					XWPFParagraph paragraph = content_row.getCell(cellNumber).getParagraphs().get(0);
					
					if(strKey.contains(no)){
	        			setAlignment(paragraph, CENTER_ALIGN, SPACING_0, SPACING_06);
	            		setTextFormat(run, counter + "", FONT_SIZE_11, false, false, FONT_TIMES_NEW_ROMAN);
	        		}
	        		if(strKey.contains(documentName)){
	        			setAlignment(paragraph, LEFT_ALIGN, SPACING_0, SPACING_06);
	        	        setTextFormat(run, attachFileDetail.getAttachFile().getAttachFileName(), FONT_SIZE_11, false, false, FONT_TIMES_NEW_ROMAN);
	        		}
	        		if(strKey.contains(documentNumber)){
	        			// SO LUONG
	        	        String numerCopy = "";
	        	        if(attachFileDetail.getNumberOfcopy() >= 10)
	        	        	numerCopy = attachFileDetail.getNumberOfcopy() + "";
	        	        else 
	        	        	numerCopy = "0"+attachFileDetail.getNumberOfcopy();

	        	        setAlignment(paragraph, CENTER_ALIGN, SPACING_0, SPACING_06);
	        	        setTextFormat(run, numerCopy, FONT_SIZE_11, false, false, FONT_TIMES_NEW_ROMAN);
	        	        
	        		}
	        		if(strKey.contains(symbolMain)){
	        	        if(WebConstants.DOC_TYPE_MAIN.equals(attachFileDetail.getDocumentType().getCode())){
	        	        	setAlignment(paragraph, CENTER_ALIGN, SPACING_0, SPACING_06);
	        	        	setTextFormat(run, WebConstants.SYMBOL_PLUS, FONT_SIZE_11, false, false, FONT_TIMES_NEW_ROMAN);
	        	        }
	        		}
	        		if(strKey.contains(symbolPhoto)){
	        	        if(WebConstants.DOC_TYPE_PHOTO.equals(attachFileDetail.getDocumentType().getCode())){
	        	        	setAlignment(paragraph, CENTER_ALIGN, SPACING_0, SPACING_06);
	        	        	setTextFormat(run, WebConstants.SYMBOL_PLUS, FONT_SIZE_11, false, false, FONT_TIMES_NEW_ROMAN);
	        	        }
	        		}
	        		if(strKey.contains(symbolMainPhoto)){
	        	        if(WebConstants.DOC_TYPE_PHOTO_WITHSEAL.equals(attachFileDetail.getDocumentType().getCode())){
	        	        	setAlignment(paragraph, CENTER_ALIGN, SPACING_0, SPACING_06);
	        	        	setTextFormat(run, WebConstants.SYMBOL_PLUS, FONT_SIZE_11, false, false, FONT_TIMES_NEW_ROMAN);
	        	        }
	        		}
	        		
					cellNumber++;
				}
        		
    	        counter++;
        	}
    	}
	}
	
	private void replaceString(XWPFParagraph xwpfParagraph, String reglex, String replacement){
		if(xwpfParagraph.getParagraphText().contains(reglex)){
			List<XWPFRun> runs = xwpfParagraph.getRuns();
			for (Iterator<XWPFRun> iterator4 = runs.iterator(); iterator4.hasNext();) {
				XWPFRun xwpfRun = (XWPFRun) iterator4.next();
				String textOfRun = xwpfRun.getText(0);
				System.out.println("=======Scan: "+textOfRun);
				if(textOfRun.contains(reglex))
					xwpfRun.setText(replacement,0);
			}
		}
	}

	public void setOrganization(String organization) {
		this.organization = organization;
	}

	public String getOrganization() {
		return organization;
	}

	public void setOrganizationTel(String organizationTel) {
		this.organizationTel = organizationTel;
	}

	public String getOrganizationTel() {
		return organizationTel;
	}

	public void setOrganizationFax(String organizationFax) {
		this.organizationFax = organizationFax;
	}

	public String getOrganizationFax() {
		return organizationFax;
	}
}
